#
import datetime

from openai import OpenAI

from spark_edu_rag.rag_qa.core.query_classifier import QAClassifier
from spark_edu_rag.rag_qa.core.rag_system import RAGSystem
from spark_edu_rag.rag_qa.core.vector_store import document_split_chunk, VectorStore
from spark_edu_rag.rag_qa.core.strategy_selector import StrategySelector
from spark_edu_rag.retrieval.bm25_search import bm25_search



from spark_edu_rag.utils import get_logger, config_ini

class IntegratedQASystem:
    def __init__(self):
        self.logger = get_logger(__name__)
        self.bm25_search = bm25_search
        self.vector_store = VectorStore()
        self.rag_system = RAGSystem(self.vector_store, self.bm25_search)
        try:
            self.client = OpenAI(
                api_key=config_ini.LLM.DASHSCOPE_API_KEY,
                base_url=config_ini.LLM.DASHSCOPE_BASE_URL,
            )
        except Exception as e:
            self.logger.error(f"初始化OpenAI客户端失败：{e}")
            raise ValueError(f"初始化OpenAI客户端失败：{e}")

    def call_dashscope(self, prompt: str) -> str:
        try:
            response = self.client.chat.completions.create(
                model=config_ini.LLM_MODEL,
                messages=[
                    {"role": "system", "content": "你是一个专业的问答助手"},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=1024,
                temperature=0.5,
            )
            return response.choices[0].message.content if response.choices else "抱歉，没有返回内容"
        except Exception as e:
            self.logger.error(f"调用DashScope失败：{e}")
            return "抱歉，没有返回内容"

    def query(self, question: str, cond : str=None) -> str:
        """
        处理用户查询，根据条件进行分类和回答
        :param question: 用户输入的问题
        :param cond: 可选的条件，用于分类查询
        :return: 模型生成的回答
        """
        start_time = datetime.datetime.now()
        self.logger.info(f"开始处理问题：{question}，条件：{cond}")
        answer = self.bm25_search.query(question, threshold=0.85)
        if answer:
            self.logger.info(f"BM25检索到相关文档，回答：{answer[:100]}，耗时：{datetime.datetime.now() - start_time}")
            return answer
        else:
            self.logger.info("BM25未检索到相关文档，切换到RAG系统")
            answer = self.rag_system.generate_answer(question, cond)
            if answer:
                self.logger.info(f"RAG系统生成回答：{answer[:100]}，耗时：{datetime.datetime.now() - start_time}")
                return answer
            else:
                self.logger.error(f"RAG系统生成回答为空")
                return "抱歉，没有返回内容"

def main():
    # 初始化数据库客户端
    qa_system = IntegratedQASystem()
    # 用户可以交互式输入问题，输入exit退出
    while True:
        question = input("请输入问题（输入exit退出）：").strip()
        if question.lower() == 'exit':
            break
        cond = input("请输入条件（可选）：").strip()
        try:
            answer = qa_system.query(question, cond)
            print(answer)
        except Exception as e:
            qa_system.logger.error(f"星火教育RAG查询系统，出错：{e}")
            print("抱歉，星火教育RAG查询系统，出错了，请查看账户余额或者客服")



        
if __name__ == '__main__':
    main()


